<template>
  <div>
    <div v-if="flowOpts.needFlowOpt && ( !formOpts.formReadOnly || (formOpts.formReadOnly && flowOpts.taskId))" style="text-align:center;">
      <EmapFlowToolbar
        ref="toolbar"
        :defKey="flowOpts.defKey"
        :taskId="flowOpts.taskId"
        :gridAlias="formOpts.gridAlias"
        :formAlias="formOpts.formAlias"
        :onverify="onverify"
        :options="options"
        :onquerysetting="onquerysetting"
        @fileexistverify="fileexistverify"
        @action_complete="action_complete"
      >
      </EmapFlowToolbar>
    </div>
    <div v-else-if="formOpts.formReadOnly && !itemData.isformMenu">
      <footer bh-role="bhFooterAffix" class="foot-center bh-clearfix" style="width: 100%; margin: auto; text-align: center;">
        <BhButton type="default" @click="closeForm()" :waves='true' :small="false">关闭</BhButton>
      </footer>
    </div>
    <div v-else>
      <footer bh-role="bhFooterAffix" class="foot-center bh-clearfix" style="width: 100%; margin: auto; text-align: center;">
        <BhButton type="primary" @click="submitForm()" :waves='true' :small="false" v-if="!formOpts.formReadOnly">保存</BhButton>
        <BhButton type="default" @click="closeForm()" :waves='true' :small="false" v-if="!itemData.isformMenu">关闭</BhButton>
      </footer>
    </div>
  </div>
</template>

<script>
import { BhButton } from 'bh-vue'
import pageUtil from '../../lib/bh-vue/utils/pageUtil'
import EmapFlowToolbar from 'components/emap-flow-toolbar'

export default {
  components: {
    /* eslint-disable-next-line */
    EmapFlowToolbar,
    BhButton
  },
  data() {
    return {
      isMuiltpart: false,
      rules: {readonly: false},  //模拟数据
      URLArr: [{
          value: 'start',
          url: '/sys/emapflow/tasks/startFlow.do'
      }, {
          value: 'submit',
          url: '/sys/emapflow/tasks/execute.do'
      }, {
          value: 'draft',
          url: '/sys/emapflow/tasks/startFlow.do'
      }, {
          value: 'turnback',
          url: '/sys/emapflow/tasks/turnback.do'
      }, {
          value: 'processStatus',
          url: '/sys/emapflow/tasks/queryFlowState.do'
      }, {
          value: 'changeAssignee',
          url: '/sys/emapflow/tasks/changeAssignee.do'
      }, {
          value: 'callback',
          url: '/sys/emapflow/tasks/callback.do'
      }, {
          value: 'termination',
          url: '/sys/emapflow/tasks/terminateInstance.do'
      }],
    }
  },
  props: {
    flowOpts: Object,
    formOpts: Object,
    otherOpts: Object,
    itemData: Object,
    formUrl: String,
    formContentRef: Object,
    formFooterRef: Object,
    processedFormData: Object,
    flowComment: Object,
    options: Object
  },
  computed: {
    
  },
  methods: {
    onverify(item){
      const canPassCommandType = ["processStatus", "urgent", "addAssigneeTask", "deleteAssigneeTask","processTrack"];
      if (canPassCommandType.indexOf(item.commandType) > -1) {
          return true;
      }
      setTimeout(()=>{
        this.onverifyFn(item)
      },1000)
    },
    onverifyFn(item){
      const _this = this
      // 合并下一步办理人组件数据
      const emapFlowToolbar = _this.$refs.toolbar.$refs.emapFlowToolbar;
      let formNode = _this.formContentRef.$refs["multipart_form"];

      // 跳过自定义的命令按钮
      const canPassCommandType = ["processStatus", "urgent", "addAssigneeTask", "deleteAssigneeTask","processTrack"];
      if (canPassCommandType.indexOf(item.commandType) > -1) {
          return true;
      }

      // 存在文件上传时，处理form数据
      if (_this.isMuiltpart === true) {
          formNode.action = window.contextPath + item.url;
          var nodes = formNode.childNodes;
          for (var i = nodes.length - 1; i >= 0; i--) {
            var node = nodes[i];
            formNode.removeChild(node);
          }

          let obj = this.onquerysetting(item)
          
          var input;
          for (var key in obj) {
            input = document.createElement('input');
            input.type = "hidden";
            input.name = key;
            input.value = obj[key];
            formNode.appendChild(input);
          }
      }
      // 保存草稿时，跳过验证;流程转办，弹出Modal获取assignee参数
      if (item.commandType === 'draft') {
          if (_this.isMuiltpart === true) {
              formNode.submit();
          } else {
              emapFlowToolbar[item.execute](item);
          }
      } else if (item.commandType === 'changeAssignee') {
          // 流程转办,特殊处理，弹出Model层,表单只读不需要校验  formReadOnly 
          if (this.isEmptyObject(this.rules)) {
              return true
          } else {
              let valid = _this.formContentRef.$refs.form.validate({$toolbar: item})
              if (valid) {
                emapFlowToolbar[item.execute](item);
              }
          }
      } else {
          // formReadOnly || this.isEmptyObject(this.rules)  //之前判断逻辑
          if (this.isEmptyObject(this.rules)) {

            if (_this.isMuiltpart === true) {
              formNode.submit();
            } else {
                emapFlowToolbar[item.execute](item);
            }
            emapFlowToolbar.buttons.map(function(btn) {
                if (btn.id === item.id) {
                    btn.disabled = true;
                }
                return btn
            });
            emapFlowToolbar.$set(emapFlowToolbar.buttons);
          } else {
              let valid = _this.formContentRef.$refs.form.validate({$toolbar: item})
              if (valid) {
                if (_this.isMuiltpart === true) {
                    formNode.submit();
                } else {
                    emapFlowToolbar[item.execute](item);
                }
                emapFlowToolbar.buttons.map(function(btn) {
                    //按钮置为不可选
                    if (btn.id === item.id) {
                        btn.disabled = true;
                    }
                    return btn
                });
                emapFlowToolbar.$set(emapFlowToolbar.buttons);
              }
          }
      }
    },
    onquerysetting(item) {
      // 获取当前item的url,如果不存在则去固定数据里面进行匹配
      if (!item.url) {
          const currentUrl = this.URLArr.filter(function(obj) {
              return obj.value === item.commandType
          });
          item.url = currentUrl[0].url;
      }

      let obj = Object.assign({},item);
      const formData = this.formContentRef.$refs.form.getValue();
      let {comment, approval_display, elecseal, nextAssignees, nextNodeId} = formData;
      obj.flowComment = "";
      if(formData.approval == null)  delete formData.approval;
      if(!elecseal) delete formData.elecseal;
      if(comment != null || approval_display != null) obj.flowComment = comment || approval_display;
      if(comment != null && approval_display != null) obj.flowComment = approval_display + "," + comment;
      if(approval_display) formData.approval = approval_display;
      if(nextAssignees) obj.nextAssignees = nextAssignees;
      if(nextNodeId) obj.nextNodeId = nextNodeId;

      delete formData.approval_display
      delete formData.nextAssignees
      delete formData.nextNodeId
      delete formData.comment
      
      obj.formData = formData;
      if(obj.formData && this.flowOpts.key && this.flowOpts.key.bizKey){
        obj.formData["WID"] = this.flowOpts.key.bizKey
      }
      obj.formData = JSON.stringify(obj.formData);
      obj.taskId = this.flowOpts.taskId;
      obj.defKey = this.flowOpts.defKey;
      obj.alias = this.formOpts.formAlias;
      obj.gridAlias = this.formOpts.gridAlias;

      return obj
    },
    fileexistverify() {
      const _this = this
      if (_this.isMuiltpart === true) {
        const formNode = _this.formContentRef.$refs["multipart_form"];
        const input = document.createElement('input');
        input.type = "hidden";
        input.name = "assignee";
        input.value = _this.itemData.assignee;
        formNode.appendChild(input);
        formNode.submit();
        return true;
      }
    },
    action_complete(type, data) {
      const _this = this
      if (type !== "processStatus" && type !== "process_track") {
        if (data.data.succeed) {
          pageUtil.tip("操作成功！","success")
          pageUtil.hidePaper()
          if(window.formOnly){
            this.closeWindow()
          }else{
            _this.$emit("save-success", _this.itemData)
          }
        } else {
          pageUtil.tip("操作失败！","error")
        }
      }
    },
    submitForm() {
      const _this = this
      const formComp = this.formContentRef.$refs.form
      let result = formComp.businessValidator()
      if (!result['ret']) return pageUtil.tip(result.tip, 'warning')
      if(formComp.validate() === true){
        const value = formComp.getValue()
        // Object.assign(value, nextAssignees);
        // Object.assign(obj, nextNodeId);
        
        const saveFormUrl = _this.formUrl.replace("showForm.do","saveForm.do")
        let params = {
          url:  window.contextPath + saveFormUrl+"?alias="+_this.itemData.form +"&gridAlias="+ _this.formOpts.gridAlias,
          type: "POST",
          data: {
          key: JSON.stringify(_this.flowOpts.key),
          data: JSON.stringify(value)
          },
          success: function(res){
          res = JSON.parse(res)
          if(res.code === "0"){
            pageUtil.tip("保存成功","success")
            pageUtil.hidePaper()
            if(window.formOnly){
              this.closeWindow()
            }else{
              _this.$emit("save-success", _this.itemData)
            }
            // _this.saveSuccess()
          }else{
            pageUtil.tip("保存失败","danger")
          }
          },
          error: function(e){
            pageUtil.tip(e, "danger")
          },
        }
        $(formComp.$el).ajaxSubmit(params);
      }
    },
    initFile(){
      //格式化初始值
      const _this = this
      let isshowtoolbar = {}
      let meta = _this.formOpts.meta
      for (var i = 0; i < meta.length; i++) {
          var key = meta[i].name;
          if (meta[i].dataType === "Clob") {
            _this.isMuiltpart = true;
            // if(_this.formFooterRef){
            //   _this.formFooterRef.isMuiltpart = true
            // }
          }
          if (meta[i].url !== undefined) {
              meta[i].dict = {
                  url: meta[i].url
              }
          }
          if (meta[i].ref !== undefined) {
              if (meta[i].manageSub) {
                  isshowtoolbar[key] = meta[i].manageSub;
              } else {
                  isshowtoolbar[key] = "";
              }
              meta[i].ref = meta[i].ref.map(function(item) {
                  if (item.url !== undefined) {
                      item.dict = {
                          url: item.url
                      }
                  }
                  item.key = item.title = item.name;
                  item.minWidth = 120;
                  item.ellipsis = true;
                  item.tooltip = true;
                  return item;
              });
          }
      }

      // iframe 获取结果的处理
      function dealWithContent(iframe) {
          var content = iframe.contentWindow.document.body.innerHTML;
          content = content.match(/{.*}/g) ? content.match(/{.*}/g)[0] : null;
          if (content) {
              var data = JSON.parse(content);
              if (data.succeed) {
                  pageUtil.tip("操作成功","success")
                  pageUtil.hidePaper()
                  if(window.formOnly){
                    _this.closeWindow()
                  }else{
                    _this.$emit("save-success", _this.itemData)
                  }
              } else {
                  pageUtil.tip("操作失败","error");
              }
          }else{
            pageUtil.tip("操作失败","error");
          }
      }

      // 监听表单上传接口返回信息iframe（#upload_pipe）的内容
      var iframe = document.getElementById('upload_pipe');
      if (iframe.attachEvent) {
          iframe.attachEvent("onload", function() {
              dealWithContent(iframe)
          });
      } else {
          iframe.onload = function() {
              dealWithContent(iframe)
          };
      }
    },
    closeForm() {
        pageUtil.hidePaper()
    },
    closeTimeout() {
      if(navigator.userAgent.indexOf("Firefox") != -1 || navigator.userAgent.indexOf("Chrome") != -1){
        window.location.href = "about:blank";
        window.close();
      }else{
        window.opener = null;
        window.open("", "_self");
        window.close();
      }
    },
    closeWindow() {
      const _this = this
      setTimeout(function(){
        _this.closeTimeout()
      },1000)
    },
    // 空对象判断
    isEmptyObject: function(obj) {
      for (const key in obj) {
        return false;
      }
      return true;
    },
    setIsMuiltpart(value){
      this.isMuiltpart = value
    }
  },
  mounted() {
    
  },
  created() {

  },
}
</script>
